package model

import (
	"common/helper"
	myUserHelp "common/userHelp"
	"database/sql"
	"fmt"
	g "github.com/doug-martin/goqu/v9"
	"github.com/valyala/fasthttp"
	"strconv"
	"time"
)

type tblDeposit struct {
	Id           string  `json:"id" db:"id" cbor:"id"`
	Oid          string  `json:"oid" db:"oid" cbor:"oid"`
	Uid          string  `json:"uid" db:"uid" cbor:"uid"`
	ParentId     string  `json:"parent_id" db:"parent_id" cbor:"parent_id"`
	Fid          string  `json:"fid" db:"fid" cbor:"fid"`
	Fname        string  `json:"fname" db:"fname" cbor:"fname"`
	Amount       string  `json:"amount" db:"amount" cbor:"amount"`
	State        int     `json:"state" db:"state" cbor:"state"`
	CreatedAt    int64   `json:"created_at" db:"created_at" cbor:"created_at"`
	ConfirmAt    int64   `json:"confirm_at" db:"confirm_at" cbor:"confirm_at"`
	ConfirmUid   string  `json:"confirm_uid" db:"confirm_uid" cbor:"confirm_uid"`
	ConfirmName  string  `json:"confirm_name" db:"confirm_name" cbor:"confirm_name"`
	ReviewRemark string  `json:"review_remark" db:"review_remark" cbor:"review_remark"`
	Discount     float64 `json:"discount" db:"discount" cbor:"discount"`
	IsFirst      int     `json:"is_first" db:"is_first"`
	IsReceived   int     `json:"is_received" db:"is_received"`
	PixAccount   string  `json:"pix_account" db:"pix_account"`
	RealName     string  `json:"real_name" db:"real_name"`
	Hidden       int     `json:"hidden" db:"hidden"`

	HiddenAmount float64 `json:"hidden_amount" db:"hidden_amount"`
}

type DepositHistoryParam struct {
	ID          string `json:"id"`
	Uid         string `json:"uid"`
	Username    string `json:"username"`
	Pid         string `json:"pid"`
	ParentName  string `json:"parent_name"`
	State       int    `json:"state"`
	OID         string `json:"oid"`
	Fid         string `json:"fid"`
	TimeFlag    uint8  `json:"time_flag"` // 时间类型  1:创建时间 0:完成时间
	TimeType    string `json:"time_type"`
	StartTime   string `json:"start_time"` // 查询开始时间
	EndTime     string `json:"end_time"`   // 查询结束时间
	MinAmount   string `json:"min_amount"` //
	MaxAmount   string `json:"max_amount"` //
	Page        int    `json:"page"`       // 页码
	PageSize    int    `json:"page_size"`  // 页大小
	Dty         int    `json:"dty"`
	OderBY      string `json:"order_by"`
	OderType    string `json:"order_type"`
	OperatorId  string `json:"operator_id"` //渠道id
	BusinessId  string `json:"business_id"` //业务员id
	ExportExcel int    `json:"export_excel"`
	IsReceived  int    `json:"is_received" db:"is_received"`
	IsFirst     string `json:"is_first" db:"is_first"`
	Hidden      int    `json:"hidden" db:"hidden"`
}

// 存款数据
type DepositData struct {
	T int64        `json:"total"`
	D []tblDeposit `json:"d"`
	S DepositSum   `json:"s"`
}
type DepositSum struct {
	TotalAmount   float64 `db:"total_amount" json:"total_amount"`
	TotalNum      int     `db:"total_num" json:"total_num"`
	SuccessAmount float64 `db:"success_amount" json:"success_amount"`
	SuccessNum    int     `db:"success_num" json:"success_num"`
	TotalPerson   float64 `db:"total_person" json:"total_person"`
	SuccessPerson float64 `db:"success_person" json:"success_person"`
}

// 存款记录
func DepositList(param DepositHistoryParam, ctx *fasthttp.RequestCtx) (DepositData, error) {
	data := DepositData{}
	where := "1=1"
	oderBy := "a.created_at"
	oderType := "desc"
	if param.Uid != "" {
		where += " and a.uid=" + param.Uid
	}
	if param.ID != "" {
		where += " and a.id=" + param.ID
	}
	if param.Pid != "" {
		where += " and h.parent_id=" + param.Pid
	}
	if param.State > 0 {
		where += " and a.state=" + strconv.Itoa(param.State)
	}
	if param.IsFirst != "" {
		where += " and a.is_first=" + param.IsFirst
	}
	if param.MinAmount != "" {
		where += " and a.amount>=" + param.MinAmount
	}
	if param.MaxAmount != "" {
		where += " and a.amount<=" + param.MaxAmount
	}
	timeStr := "created_at"
	if param.TimeType == "1" {
		timeStr = "confirm_at"
	}
	if param.StartTime != "" {
		StartTime, _ := helper.TimeToLoc(param.StartTime, loc)
		where += " and a." + timeStr + ">='" + strconv.FormatInt(StartTime, 10) + "'"
	}
	if param.EndTime != "" {
		EndTime, _ := helper.TimeToLoc(param.EndTime, loc)
		where += " and a." + timeStr + "<='" + strconv.FormatInt(EndTime, 10) + "'"
	}

	if param.OderBY != "" {
		oderBy = param.OderBY
	}
	if param.OderType != "" {
		oderType = param.OderType
	}

	loginUser := GetLoginUser(ctx)
	if loginUser.Operator != "" {
		where += " and b.operator_id=" + loginUser.Operator
	}
	if loginUser.Businsess != "" {
		where += " and b.business_id=" + loginUser.Businsess
	}

	table := "tbl_deposit"
	join := " left join tbl_member_base as b on b.uid=a.uid" //玩家表
	//join += " left join tbl_operator_info as c on c.id=b.operator_id" //渠道表
	//join += " left join tbl_business_info as d on d.id=b.business_id" //业务员表
	//join += " left join tbl_pay_factory as g on g.fid=a.fid"
	join += " left join tbl_proxy_base as h on h.uid=a.uid"

	order := oderBy + " " + oderType

	offset := (param.Page - 1) * param.PageSize
	if param.Page >= 1 {
		count := "select count(1) from " + table + " as a " + join + " where " + where

		err := meta.MerchantDB.Get(&data.T, count)
		if err != nil {

			return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), count), "数据库错误")
		}
		if (data.T) == 0 {
			return data, nil
		}
	}

	field := "a.*"
	query := "select " + field + " from " + table + "  as a " + join + " where " + where + " order by " + order + " limit " + strconv.Itoa(param.PageSize) + " offset " + strconv.Itoa(offset)

	err := meta.MerchantDB.Select(&data.D, query)
	if err != nil && err != sql.ErrNoRows {

		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}

	if param.ExportExcel == 1 {
		return data, nil
	}

	//总统计
	sfield := "ifnull(sum(a.amount),0) total_amount," +
		"count(1) total_num,count(distinct a.uid) total_person"
	query = "select " + sfield + " from " + table + " as a " + join + " where " + where

	err = meta.MerchantDB.Get(&data.S, query)
	//成功统计
	sfield = "ifnull(sum(a.amount),0) success_amount," +
		"count(1) success_num,count(distinct a.uid) success_person"
	query = "select " + sfield + " from " + table + " as a " + join + " where (a.state=362 or a.state=365) and " + where

	err = meta.MerchantDB.Get(&data.S, query)
	if err != nil && err != sql.ErrNoRows {
		return data, pushLog(fmt.Errorf("%s,[%s]", err.Error(), query), "数据库错误")
	}
	return data, nil
}

// 充值列表数据处理
func RechargeListOpt(data DepositData, exportExcel int) (DepositData, [][]interface{}) {
	exportData := [][]interface{}{}
	for _, value := range data.D {
		if exportExcel == 1 {
			state := ""
			switch value.State {
			case 361:
				state = "待确认"
			case 362:
				state = "充值成功"
			case 363:
				state = "已取消"
			case 365:
				state = "补单成功"
			}
			single := []interface{}{
				value.Id,
				value.Uid,
				value.Amount,
				state,
				time.Unix(value.CreatedAt, 0).Format("2006-01-02 15:04:05"),
			}
			exportData = append(exportData, single)
		}
	}
	return data, exportData
}

type OrderUserId struct {
	Uid   string `json:"uid" db:"uid" cbor:"uid"`
	State int    `json:"state" db:"state" cbor:"state"`
}

func UpdateOrderFinish(orderid string, status int, ctx *fasthttp.RequestCtx) error {

	orderuid := OrderUserId{}
	query, _, _ := dialect.From("tbl_deposit").Select("uid", "state").Where(g.Ex{"id": orderid}).Limit(1).ToSQL()

	err := meta.MerchantDB.Get(&orderuid, query)
	if err != nil {
		return pushLog(err, "数据库错误")
	}

	if orderuid.State != 361 {
		return pushLog(err, helper.OrderStateErr)
	}
	err = myUserHelp.DepositUpPointSuccess(orderid, orderuid.Uid, strconv.Itoa(status))

	if err != nil {
		return err
	}
	return nil
}

func UpdateHiddenOrder(orderid string, hidden int, ctx *fasthttp.RequestCtx) error {

	query, _, _ := dialect.Update("tbl_deposit").Set(g.Record{"hidden": hidden}).Where(g.Ex{"id": orderid}).ToSQL()
	_, err := meta.MerchantDB.Exec(query)
	if err != nil {
		return pushLog(err, "数据库错误")
	}

	if err != nil {
		return err
	}
	return nil
}
